package com.adminsystem.service.impl;

import com.adminsystem.common.utils.StringUtils;
import com.adminsystem.entity.SysMenu;
import com.adminsystem.entity.SysRole;
import com.adminsystem.entity.custom.PageBean;
import com.adminsystem.mapper.SysMenuMapper;
import com.adminsystem.mapper.SysRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.adminsystem.entity.SysUser;
import com.adminsystem.service.SysUserService;
import com.adminsystem.mapper.SysUserMapper;
import com.system.common.utils.PoiUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【sys_user(用户表)】的数据库操作Service实现
 * @createDate 2023-09-20 18:11:18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
        implements SysUserService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser getByUserName(String username) {
        return getOne(new QueryWrapper<SysUser>().eq("username", username).ne("is_delete","1"));
    }


    @Override
    public String getUserAuthorityInfo(long userId) {
        StringBuilder authority = new StringBuilder();
        //根据用户id获取所有角色信息
        List<SysRole> roleList = sysRoleMapper.selectList(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id=" + userId));
        if (roleList.size() > 0) {
            String roleCodeStrs = roleList.stream().map(r -> "ROLE_" + r.getCode()).collect(Collectors.joining(","));
            authority.append(roleCodeStrs);
        }
        //遍历所有的角色，获取所有菜单权限而且不重复
        Set<String> menuCodeSet = new HashSet<>();
        for (SysRole sysRole : roleList) {
            List<SysMenu> menuList = sysMenuMapper.selectList(new QueryWrapper<SysMenu>().inSql("id", "select menu_id from sys_role_menu where role_id=" + sysRole.getId()));
            for (SysMenu sysMenu : menuList) {
                String perms = sysMenu.getPerms();
                if (StringUtils.isNotEmpty(perms)) {
                    menuCodeSet.add(perms);
                }
            }
        }
        if (menuCodeSet.size() > 0) {
            authority.append(",");
            String menuCodeStrs = String.join(",", menuCodeSet);
            authority.append(menuCodeStrs);
        }
        System.out.println("authority:" + authority);
        return authority.toString();
    }

    @Override
    public File createUserExcelFile(PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        List<SysUser> userList = sysUserMapper.selectList(
                new QueryWrapper<SysUser>().like(StringUtils.isNotEmpty(query), "username", query).ne("is_delete","1").orderByDesc("update_time").last("limit " + pageBean.getPageNum() + "," + pageBean.getPageSize()));
        for (SysUser user : userList) {
            List<SysRole> roleList = sysRoleMapper.selectList(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id= " + user.getId()));
            user.setSysRoleList(roleList);
            user.setSysRoleStr((roleList.stream().map(SysRole::getName)).collect(Collectors.joining(",")));
        }
        return createUserExcelFile(userList);
    }
    public static File createUserExcelFile(List<?> records) {
        if (records == null) {
            records = new ArrayList<>();
        }
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        Row row0 = sheet.createRow(0);
        int columnIndex = 0;
        row0.createCell(columnIndex).setCellValue("No");
        row0.createCell(++columnIndex).setCellValue("ID");
        row0.createCell(++columnIndex).setCellValue("用户名");
        row0.createCell(++columnIndex).setCellValue("手机号");
        row0.createCell(++columnIndex).setCellValue("头像");
        row0.createCell(++columnIndex).setCellValue("角色");
        row0.createCell(++columnIndex).setCellValue("邮箱");
        row0.createCell(++columnIndex).setCellValue("状态");
        row0.createCell(++columnIndex).setCellValue("最后登录时间");
        row0.createCell(++columnIndex).setCellValue("创建时间");
        row0.createCell(++columnIndex).setCellValue("更新时间");
        for (int i = 0; i < records.size(); i++) {
            SysUser user = (SysUser) records.get(i);
            Row row = sheet.createRow(i + 1);
            for (int j = 0; j < columnIndex + 1; j++) {
                row.createCell(j);
            }
            columnIndex = 0;
            row.getCell(columnIndex).setCellValue(i + 1);
            row.getCell(++columnIndex).setCellValue(user.getId());
            row.getCell(++columnIndex).setCellValue(user.getUsername());
            row.getCell(++columnIndex).setCellValue(user.getPhonenumber());
            row.getCell(++columnIndex).setCellValue(user.getAvatar());
            row.getCell(++columnIndex).setCellValue(user.getSysRoleStr());
            row.getCell(++columnIndex).setCellValue(user.getEmail());
            row.getCell(++columnIndex).setCellValue(user.getStatus());
            row.getCell(++columnIndex).setCellValue(user.getLastLoginDate());
            row.getCell(++columnIndex).setCellValue(user.getCreateTime());
            row.getCell(++columnIndex).setCellValue(user.getUpdateTime());
        }
        return PoiUtils.createExcelFile(workbook, "download_user");
    }

    @Override
    public SysUser getByPhone(String phone) {
        return getOne(new QueryWrapper<SysUser>().eq("phonenumber", phone).ne("is_delete", "1"));

    }

    @Override
    public SysUser getByEmail(String email) {
        return getOne(new QueryWrapper<SysUser>().eq("email", email).ne("is_delete", "1"));

    }
}




